package com.hwhhhh.graduationproject.resolvers;

import com.hwhhhh.graduationproject.annotation.CurrentUser;
import com.hwhhhh.graduationproject.domain.model.User;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Description CurrentUserMethodArgumentResolver   解析通过拦截器的request获取其中user，此方法使之
 * 能够直接通过 @CurrentUser 注解在controller中直接获取用户信息
 * Created by Hwhhhh on 2021/3/4 10:36
 */
public class CurrentUserMAR implements HandlerMethodArgumentResolver {
    /**
     * 用于判定是否需要处理该参数分解，返回true为需要，然后调用下面的方法resolveArgument
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(User.class)
                && methodParameter.hasParameterAnnotation(CurrentUser.class);
    }

    /**
     * 进行参数处理，返回的object即为controller上的形参对象
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        User user = (User) nativeWebRequest.getAttribute("currentUser", RequestAttributes.SCOPE_REQUEST);
        return user;
    }
}
